//
//  FKCommodityDetailVC.m
//  HappyTest
//
//  Created by Macbook Pro on 2019/2/15.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKCommodityDetailVC.h"
#import "FKPenetrateTouchTableView.h"
#import "FKCommodityBottomView.h"
#import <JXCategoryView.h>
#import "FKImageTextChildVC.h"
#import "FKShareImageTextVC.h"
#import "FKChooseAttrPopVC.h"
#import "FKShoppingCartVC.h"
#import "FKConfirmOrderVC.h"
#import "FKProductParametersPopView.h"
#import "FKGoodsShopAddressHeader.h"
#import "FKTableCell.h"
#import "FKGoodsBannerCell.h"
#import "FKGoodsInfoCell.h"
#import "FKGoodsShopAddressCell.h"
#import "FKFastShareModel.h"
#import "FKPosterPopView.h"
#import <UShareUI/UShareUI.h>
#import "FKWeakTimer.h"

@interface FKCommodityDetailVC ()<UITableViewDataSource, UITableViewDelegate, JXCategoryViewDelegate, FKCommodityBottomViewDelegate, FKGoodsBannerCellDelegate, FKGoodsInfoCellDelegate, FKGoodsShopAddressCellDelegate>

@property (nonatomic, weak) UIButton *collectBtn;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSDictionary *data;

@property (nonatomic, weak) FKCommodityBottomView *bottomView;
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, weak) FKImageTextChildVC *leftChildVC;
@property (nonatomic, weak) FKShareImageTextVC *rightChildVC;
//@property (nonatomic, assign) NSInteger countDown;
/** 售卖时间 */
@property (nonatomic, strong) NSDictionary *sale_time;

@end

@implementation FKCommodityDetailVC
//{
//    NSTimer *_timer;
//}
//
//#pragma mark - private
//- (void)startTimer
//{
//    [self removeTimer];
//    _timer = [FKWeakTimer fk_scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:true];
//    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
//    [_timer fire];
//}
//
//- (void)updateTime
//{
//    if (self.countDown > 0) {
//        self.countDown--;
//    } else {
//        [self removeTimer];
//        [self loadData];
//    }
//    FKLog(@"---开售定时器---");
//}
//
//- (void)removeTimer
//{
//    if (_timer) [_timer invalidate];
//    _timer = nil;
//}

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商品详情";
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"updateCartNum" object:nil];
    
    UIButton *collectBtn = [UIButton fk_btnWithTarget:self action:@selector(collectBtnClicked:) img:[UIImage imageNamed:@"Collect"]];
    [collectBtn setImage:[UIImage imageNamed:@"Collect_selected"] forState:UIControlStateSelected];
    collectBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    collectBtn.bounds = CGRectMake(0, 0, 44, 44);
    self.collectBtn = collectBtn;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:collectBtn];
    
    FKCommodityBottomView *bottomView = [[FKCommodityBottomView alloc] init];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    bottomView.delegate = self;
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.mas_equalTo(fk_adjustW(50));
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    // 尾部
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fkScreenH - fkStatusAndNaBarH - fk_adjustW(50))];
    
    
    NSArray *titles = @[@"图文详情", @"分享素材"];
    if (self.isPackage) {
        titles = @[@"图文详情"];
    }
    CGFloat headerH = fk_adjustW(45);
    JXCategoryTitleView *categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, headerH)];
    [footer addSubview:categoryView];
    self.categoryView = categoryView;
    categoryView.titleSelectedColor = fkMainColor;
    categoryView.delegate = self;
    categoryView.titleColorGradientEnabled = YES;
    categoryView.titles = titles;
    categoryView.titleFont = fk_adjustFont(14);
    categoryView.backgroundColor = [UIColor whiteColor];
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    categoryView.indicators = @[lineView];
    lineView.indicatorLineViewColor = fkMainColor;
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [footer addSubview:scrollView];
    self.scrollView = scrollView;
    scrollView.showsHorizontalScrollIndicator = false;
    scrollView.pagingEnabled = true;
    scrollView.bounces = false;
    
    categoryView.contentScrollView = self.scrollView;
    scrollView.contentSize = CGSizeMake(fkScreenW * titles.count, 0);
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(categoryView.mas_bottom);
    }];
    
    FKImageTextChildVC *leftChildVC = [[FKImageTextChildVC alloc] init];
    [self addChildViewController:leftChildVC];
    self.leftChildVC = leftChildVC;
    CGFloat childVCH = fkScreenH - fkStatusAndNaBarH - fk_adjustW(45) - fk_adjustW(50);
    leftChildVC.tableView.frame = CGRectMake(0, 0, fkScreenW, childVCH);
    [self.scrollView addSubview:leftChildVC.tableView];
    
    if (titles.count == 2) {
        FKShareImageTextVC *rightChildVC = [[FKShareImageTextVC alloc] init];
        [self addChildViewController:rightChildVC];
        self.rightChildVC = rightChildVC;
//        rightChildVC.itemId = self.itemId;
        rightChildVC.tableView.frame = CGRectMake(fkScreenW, 0, fkScreenW, childVCH);
        [self.scrollView addSubview:rightChildVC.tableView];
    }
    
    self.tableView.tableFooterView = footer;
    [self loadData];
}

- (void)collectBtnClicked:(UIButton *)btn
{
    [FKLoginTool checkLogin:^{
        btn.enabled = false;
        if (self.data) {
            NSString *id = self.data[@"item_info"][@"id"];
            [self updateCollect:id finish:^(BOOL success, NSString *msg) {
                btn.enabled = true;
                if ([msg isEqualToString:@"收藏成功"]) {
                    btn.selected = true;
                } else if ([msg isEqualToString:@"成功取消收藏"]) {
                    btn.selected = false;
                }
            }];
        }
    }];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 处理嵌套滚动
    [self fk_scrollViewDidScroll:scrollView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    NSArray *items = group[@"items"];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.row];
//    if ([item[@"cellName"] isEqualToString:@"FKCommodityContainerCell"]) {
//        return self.containerCell;
//    }
    FKTableCell *cell = [FKTableCell cellWith:tableView className:item[@"cellName"]];
    cell.data = item[@"data"];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.row];
    return item[@"cellH"] ? [item[@"cellH"] floatValue] : 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
//    if (group[@"isContainer"]) {
//        return self.categoryView.fk_height;
//    }
    return group[@"headerH"] ? [group[@"headerH"] floatValue] : 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"footerH"] ? [group[@"footerH"] floatValue] : 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    if (group[@"headerName"]) {
        FKGoodsShopAddressHeader *header = [FKGoodsShopAddressHeader sectionView:tableView];
        return header;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSDictionary *info = self.data[@"info"];
//    NSArray *attrs = info[@"attr"];
//    if (attrs.count == 0) {
//        [SVProgressHUD showInfoWithStatus:@"暂无参数"];
//        return;
//    }
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    if ([cell isKindOfClass:NSClassFromString(@"FKCommodityAttrCell")]) {
//        FKProductParametersPopView *view = [FKProductParametersPopView parameterView];
//        view.datas = attrs;
//        [view show];
//    }
}

#pragma mark - FKGoodsBannerCellDelegate
- (void)goodsBannerCell:(FKGoodsBannerCell *)cell didClickedGetPosterBtn:(UIButton *)btn
{
    if (self.data) {
        NSDictionary *itemInfo = self.data[@"item_info"];
//        NSString *ad_img = itemInfo[@"ad_img"];
        
        FKPosterData *data = [[FKPosterData alloc] init];
        data.picUrl = itemInfo[@"ad_img"];
#warning 回头这里记得拼接上uid
        NSDictionary *loginInfo = [FKCacheTool loginInfo];
        NSDictionary *userInfo = loginInfo[@"user_info"];
        data.qrcodeUrl = fkFORMAT(@"%@&user_id=%@", itemInfo[@"url"], userInfo[@"id"]);
        
        FKPosterPopView *view = [[FKPosterPopView alloc] init];
//        [view showWithUrl:ad_img];
        [view showWith:data];
    }
}

#pragma mark - FKGoodsInfoCellDelegate
- (void)goodsInfoCellDidClickedShareBtn:(FKGoodsInfoCell *)cell
{
    [self share];
}

#pragma mark - FKGoodsShopAddressCellDelegate
- (void)goodsShopAddressCell:(FKGoodsShopAddressCell *)cell didClickedAddress:(NSDictionary *)address
{
    [self fk_showMapAlertWithEndPoint:CLLocationCoordinate2DMake([address[@"lat"] doubleValue], [address[@"lng"] doubleValue])];
}

#pragma mark - FKCommodityBottomViewDelegate
- (void)commodityBottomView:(FKCommodityBottomView *)view didClickedItemBtn:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"首页"]) {
        [self.navigationController popToRootViewControllerAnimated:true];
    } else if ([btn.titleLabel.text isEqualToString:@"客服"]) {
        if (self.data) {
            fk_call(self.data[@"tel"]);
        }
    } else if ([btn.titleLabel.text isEqualToString:@"购物车"]) {
        fkWeakSelf(self);
        [FKLoginTool checkLogin:^{
            FKShoppingCartVC *vc = [[FKShoppingCartVC alloc] init];
            [weakself.navigationController pushViewController:vc animated:true];
        }];
    }
}

- (void)commodityBottomView:(FKCommodityBottomView *)view didClickedBuyBtn:(UIButton *)btn
{
    if (!self.data) {
        [SVProgressHUD showInfoWithStatus:@"数据加载中，请稍后"];
    }
    if (![self isCanBuy]) {
        [SVProgressHUD showInfoWithStatus:@"还未到开售时间"];
        return;
    }
    
    fkWeakSelf(self);
    [FKLoginTool checkLogin:^{
        FKChooseAttrPopVC *vc = [[FKChooseAttrPopVC alloc] init];
        vc.data = weakself.data[@"item_info"];
        vc.confirmBlock = ^(NSDictionary *param) {
            [weakself buyNow:param];
        };
        [weakself presentViewController:vc animated:false completion:nil];
    }];
}

- (void)commodityBottomView:(FKCommodityBottomView *)view didClickedShareBtn:(UIButton *)btn
{
    if (self.categoryView.titles.count > 1) {
        [self.categoryView selectItemAtIndex:1];
    }
}

- (void)commodityBottomView:(FKCommodityBottomView *)view didClickedInviteBtn:(UIButton *)btn
{
    if (self.data) {
        NSDictionary *item_info = self.data[@"item_info"];
        if ([item_info[@"is_set_meal"] isEqualToNumber:@(1)]) { // 是创业礼包
            [self share];
        } else { // 不是创业礼包
            if (self.categoryView.titles.count > 1) {
                [self.categoryView selectItemAtIndex:1];
            }
        }
    }
}

- (void)share
{
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSDictionary *itemInfo = self.data[@"item_info"];
        
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:itemInfo[@"title"] descr:itemInfo[@"title"] thumImage:itemInfo[@"img"]];
        //设置网页地址
        shareObject.webpageUrl = itemInfo[@"item_url"];

        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;

        //调用分享接口
        // UMSocialPlatformType_WechatSession、platformType
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"分享失败"];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
            }
        }];
    }];
}

- (void)commodityBottomView:(FKCommodityBottomView *)view didClickedAddCartBtn:(UIButton *)btn
{
    if (!self.data) {
        [SVProgressHUD showInfoWithStatus:@"数据加载中，请稍后"];
    }
    if (![self isCanBuy]) {
        [SVProgressHUD showInfoWithStatus:@"还未到开售时间"];
        return;
    }
    
    fkWeakSelf(self);
    [FKLoginTool checkLogin:^{
        FKChooseAttrPopVC *vc = [[FKChooseAttrPopVC alloc] init];
        vc.data = weakself.data[@"item_info"];
        vc.confirmBlock = ^(NSDictionary *param) {
            [weakself addShopingCart:param];
        };
        [weakself presentViewController:vc animated:false completion:nil];
    }];
}

- (BOOL)isCanBuy
{
    if (self.sale_time) {
        NSString *startTime = fkFORMAT(@"%@", self.sale_time[@"start_timestamp"]);
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[startTime doubleValue]];
        NSDate *currentDate = [NSDate date];
        NSComparisonResult result = [date compare:currentDate];
        return (result == NSOrderedAscending);
    }
    return true;
}

#pragma mark - 网络请求
- (void)loadData
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"item_id"] = self.itemId;
    if (![SVProgressHUD isVisible]) {
        [SVProgressHUD show];
    }
    [FKHttpTool postWithSuffix:@"m=Home&c=Item&a=details" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            self.data = result.data;
            NSDictionary *itemInfo = result.data[@"item_info"];
            NSMutableDictionary *timeDict = [NSMutableDictionary dictionaryWithCapacity:0];
            timeDict[@"saleTime"] = itemInfo[@"time_arr"][@"share_desc"][@"sale_desc"];
            timeDict[@"activeTime"] = itemInfo[@"time_arr"][@"share_desc"][@"active_desc"];
            // 有售卖时间限制
            if ([fkFORMAT(@"%@", itemInfo[@"time_arr"][@"sale_time"][@"is_no_time"]) isEqualToString:@"0"]) {
                self.sale_time = itemInfo[@"time_arr"][@"sale_time"];
            }
            
            self.collectBtn.selected = [result.data[@"collect_status"] isEqualToNumber:@(1)];
//            [self.leftChildVC setHtmlStr:itemInfo[@"info"]];
            self.leftChildVC.url = itemInfo[@"url"];
            if (!self.isPackage) {
                self.rightChildVC.datas = [FKFastShareModel mj_objectArrayWithKeyValuesArray:itemInfo[@"share"]];
                self.rightChildVC.goodsUrl = itemInfo[@"item_url"];
                self.rightChildVC.timeDict = timeDict;
                [self.rightChildVC.tableView reloadData];
            }
            
            self.bottomView.cartNum = fkFORMAT(@"%@", result.data[@"cart_num"]);
            self.bottomView.member = [FKCacheTool isMember];
            self.bottomView.special = [itemInfo[@"is_set_meal"] boolValue];
            self.bottomView.cutPrice = itemInfo[@"commission_price"];
            self.bottomView.sharePrice = itemInfo[@"share_price"];
            [self.bottomView updateTitle];
            
            NSMutableArray *datas = [NSMutableArray array];
            // banner
            NSMutableDictionary *headerGroup = [NSMutableDictionary dictionary];
            [datas addObject:headerGroup];
            
            NSMutableDictionary *bannerItem = [NSMutableDictionary dictionary];
            bannerItem[@"cellName"] = @"FKGoodsBannerCell";
            NSMutableDictionary *bannerData = [NSMutableDictionary dictionary];
            bannerData[@"item_type"] = itemInfo[@"item_type"];
            bannerData[@"hidePostImg"] = @(!([FKCacheTool isMember] && !self.isPackage));
            NSArray *vice_img = itemInfo[@"vice_img"];
            NSMutableArray *images = [NSMutableArray array];
            for (NSDictionary *imgDict in vice_img) {
                [images addObject:imgDict[@"url"]];
            }
            bannerData[@"images"] = images;
            bannerData[@"active_datestring_desc"] = itemInfo[@"active_datestring_desc"];
            bannerData[@"sale_start_status"] = itemInfo[@"sale_start_status"];
            bannerData[@"sale_start_name"] = itemInfo[@"sale_start_name"];
            bannerData[@"sale_start_time"] = itemInfo[@"sale_start_time"];
            bannerItem[@"data"] = bannerData;
            CGFloat bannerCellH = fkScreenW * 0.5;
            bannerItem[@"cellH"] = @(bannerCellH);
            
            NSMutableDictionary *infoItem = [NSMutableDictionary dictionary];
            infoItem[@"cellName"] = @"FKGoodsInfoCell";
            infoItem[@"data"] = itemInfo;
            
            NSString *title = itemInfo[@"title"];
            CGFloat titleH = [title boundingRectWithSize:CGSizeMake(fkScreenW - 12 - 8 - fk_adjustW(49), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : fk_adjustFont(14)} context:nil].size.height;
            
            NSString *price = itemInfo[@"price"];
            CGFloat priceH = [price sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(20)}].height;
            
            NSString *marketPrice = itemInfo[@"marketprice"];
            CGFloat marketPriceH = [marketPrice sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(12)}].height;
            
            NSString *sales = itemInfo[@"sales"];
            CGFloat salesH = [sales sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(12)}].height;
            
            CGFloat infoCellH = fk_adjustW(12) + titleH + fk_adjustW(10) + priceH + fk_adjustW(10) + marketPriceH + fk_adjustW(10) + salesH + fk_adjustW(10);
            infoItem[@"cellH"] = @(infoCellH);
            headerGroup[@"items"] = @[bannerItem, infoItem];
            
            // 活动时间
            NSMutableDictionary *timeGroup = [NSMutableDictionary dictionary];
            [datas addObject:timeGroup];
            CGFloat timeHeaderH = fk_adjustW(10);
            timeGroup[@"headerH"] = @(timeHeaderH);
            
            NSMutableDictionary *timeItem = [NSMutableDictionary dictionary];
            timeGroup[@"items"] = @[timeItem];
            CGFloat timeCellH = fk_adjustW(65);
            timeItem[@"cellH"] = @(timeCellH);
            timeItem[@"cellName"] = @"FKGoodsTimeCell";
            NSMutableDictionary *timeData = [NSMutableDictionary dictionary];
            timeData[@"saleTime"] = itemInfo[@"time_arr"][@"sale_time"][@"desc"];
            timeData[@"activeTime"] = itemInfo[@"time_arr"][@"active_time"][@"desc"];
//            timeData[@"active_datestring_desc"] = itemInfo[@"active_datestring_desc"];
//            timeData[@"sale_start_status"] = itemInfo[@"sale_start_status"];
//            timeData[@"sale_start_name"] = itemInfo[@"sale_start_name"];
//            timeData[@"sale_start_time"] = itemInfo[@"sale_start_time"];
            timeItem[@"data"] = timeData;
            
            // 店铺信息【售货地址】
            NSArray *seller_address = itemInfo[@"seller_address"];
            
            NSMutableDictionary *shopGroup = [NSMutableDictionary dictionary];
            [datas addObject:shopGroup];
            CGFloat addressHeaderH = fk_adjustW(46);
            shopGroup[@"headerH"] = @(addressHeaderH);
            shopGroup[@"headerName"] = @"FKGoodsShopAddressHeader";
            shopGroup[@"footerH"] = @(fk_adjustW(10));
            
            CGFloat addressItemsH = 0;
            if (seller_address.count > 0) {
                NSMutableArray *addressItems = [NSMutableArray array];
                for (NSInteger index = 0; index < seller_address.count; index++) {
                    NSMutableDictionary *addressItem = [NSMutableDictionary dictionary];
                    [addressItems addObject:addressItem];
                    addressItem[@"cellName"] = @"FKGoodsShopAddressCell";
                    addressItem[@"data"] = seller_address[index];
                    addressItem[@"cellH"] = @(fk_adjustW(44));
                    addressItemsH += fk_adjustW(44);
                }
                shopGroup[@"items"] = addressItems;
            }
            
            self.criticalPointOffsetY = bannerCellH + infoCellH + timeHeaderH + timeCellH + addressHeaderH + addressItemsH + fk_adjustW(10);
            self.datas = datas;
            [self.tableView reloadData];
        }
    } failure:nil];
}

- (void)updateCollect:(NSString *)collectId finish:(void (^)(BOOL success, NSString *msg))finish
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"item_id"]= collectId;
    [FKHttpTool postWithSuffix:@"m=Home&c=Mine&a=add_collect" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:result.msg];
        }
        if (finish) finish(result.isSuccess, result.msg);
    } failure:^(NSError *error) {
        if (finish) finish(false, nil);
    }];
}

// 立即购买
- (void)buyNow:(NSDictionary *)goodsData
{
    [SVProgressHUD show];
    NSMutableDictionary *mutableGoodsData = [NSMutableDictionary dictionaryWithDictionary:goodsData];
    if (self.isPackage) mutableGoodsData[@"is_set_meal"] = @"1";
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"goods"] = mutableGoodsData;
    [FKHttpTool postWithSuffix:@"m=Home&c=Orders&a=create" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            FKConfirmOrderVC *vc = [[FKConfirmOrderVC alloc] init];
            vc.confirmDict = result.data;
            vc.orderParam = mutableGoodsData;
            fkPushNav(vc);
        }
    } failure:nil];
}

// 加入购物车
- (void)addShopingCart:(NSDictionary *)data
{
    [SVProgressHUD show];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"item_id"] = data[@"goods_id"];
    param[@"item_num"] = data[@"nums"];
    param[@"option_id"] = data[@"option_id"];
    [FKHttpTool postWithSuffix:@"m=Home&c=Cart&a=addCart" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"加入购物车成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCartNum" object:nil userInfo:@{@"cartNum" : result.data[@"car_num"]}];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadData];
            });
        }
    } failure:nil];
}

@end
